import { createRouter, createWebHistory } from 'vue-router';
import { storeToRefs } from 'pinia';
import useStore from "@/store";

const routes = [
	{ path: '/', redirect: '/login' },
	{ path: '/todo', redirect: '/todo/all' },
	{
		name: 'login',
		path: '/login',
		component: () => import('@/views/Login.vue'),
	},
	{
		name: 'edit',
		path: '/edit',
		component: () => import('@/views/Edit.vue'),
	},
	{
		name: 'todoAll',
		path: '/todo/all',
		component: () => import('@/views/Todo.vue'),
	},
	{
		name: 'todoActive',
		path: '/todo/active',
		component: () => import('@/views/Todo.vue'),
	},
	{
		name: 'todoCompelete',
		path: '/todo/compelete',
		component: () => import('@/views/Todo.vue'),
	},
]

const router = createRouter({
	routes,
	history: createWebHistory(),
});

router.beforeEach((to: any, from: any, next: any) => {
	const { user } = useStore();
	const { success } = storeToRefs(user);
	if (!success.value && to.name !== 'login')
		router.replace('/login');
	else if (success.value && to.name === 'login')
		router.replace('/edit');
	next();
})

export default router;
